package net.yebaihe.wc;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ShowSessionDetail extends StateMachine{

	private SQLiteDatabase listdb;
	private ListView lstSessionDetail;
	private TextView txtTotal;
	protected int selectNo;

	class AssetToSDRunnable implements Runnable{

		private int id;

		public AssetToSDRunnable(int id) {
			this.id=id;
		}

		@Override
		public void run() {
			AssetManager am = ShowSessionDetail.this.getAssets();
			try {
				InputStream is = am.open(id+".dat");
				String path=getLocalDishPath(id);
				File fd=new File(path);
				if (!fd.exists()){
					FileOutputStream os = new FileOutputStream(path);
					byte[] buf = new byte[1024];
					int n = 0;
					int o = 0;
					while ((n = is.read(buf, o, buf.length)) != -1) {
						os.write(buf, 0, n);
					}
					is.close();
					os.close();
				}

				File ft=new File(path+".thumb");
				if (!ft.exists()){
					Bitmap thumb=Bitmap.createScaledBitmap(BitmapFactory.decodeFile(path), 50, 50, true);
					try {
						FileOutputStream out = new FileOutputStream(path+".thumb");
						thumb.compress(Bitmap.CompressFormat.PNG, 90, out);
						out.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
					refreshSessionDetail();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

	
	class SessionSimpleCursorAdapter extends SimpleCursorAdapter{

		public SessionSimpleCursorAdapter(Context dishes, int itemdish, Cursor c,
				String[] strings, int[] is) {
			super(dishes,itemdish,c,strings,is);
		}
		
		@Override  
		public void bindView(View view, Context context, Cursor cursor) {  
			super.bindView(view, context, cursor);

			if (cursor.getPosition() % 2==0){
				//view.setBackgroundColor(R.drawable);
				view.setBackgroundResource(R.drawable.rest_bg_1);
			}
			else{
				//view.setBackgroundColor(0xFFdde4f6);
				view.setBackgroundResource(R.drawable.rest_bg_2);

			}
			
			ImageView img=(ImageView) view.findViewById(R.id.imagethumb);
			img.setTag(getLocalDishPath(cursor.getInt(0)));
			img.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View arg0) {
					Log.d("", arg0.getTag().toString());
					showBigImage(arg0.getTag().toString());
				}
			});
			File f=new File(getLocalDishPath(cursor.getInt(0))+".thumb");
			if (f.exists()){
				img.setImageBitmap(BitmapFactory.decodeFile(f.getAbsolutePath()));
			}
			else{
				new Handler().postDelayed(new AssetToSDRunnable(cursor.getInt(0)), 100);
			}
			
			if (listdb!=null){
				Cursor c=listdb.rawQuery("select users.username,count from (select *,sum(total) as count from sessiondish where sessionid="+
							getWCAppContext().sessionid+" and dishid="+cursor.getLong(0)+" group by fromuid) as ta,users where ta.fromuid=users._id", null);
				String t="";
				while (c.moveToNext()){
					t+=c.getString(0)+" ";
				}
				TextView v=(TextView) view.findViewById(R.id.txtorders);
				v.setText(t);
				c.close();
			}
			
		}
	}

	public String getLocalDishPath(int id) {
		String basedir=Environment.getExternalStorageDirectory()+"/weican/dishes/"+getIntent().getLongExtra("restaurant",-1)+"/";
		File f=new File(basedir);
		if (!f.exists()) f.mkdirs();
		//Log.d("", basedir+id+".dat");
		return basedir+id+".dat";
	}
	
	@Override
	protected String getTopbarTitle() {
		String title="未知聚餐";
		SQLiteDatabase db = MyHelper.get(this).getReadableDatabase();
		if (db!=null){
			Cursor c=db.rawQuery("select * from sessions where _id="+getIntent().getIntExtra("sessionid", -1), null);
			if (c.moveToFirst()){
				title=c.getString(3);
			}
			c.close();
			db.close();
		}
		return title;
	}

	@Override
	protected void prepareClient(View client) {
		listdb=MyHelper.get(this).getReadableDatabase();
		lstSessionDetail=(ListView)client.findViewById(R.id.lstsessiondetail);
		txtTotal=(TextView)client.findViewById(R.id.txtTotal);
		refreshSessionDetail();
		
		Button btnSns=(Button) client.findViewById(R.id.btnsns);
		btnSns.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				getWCAppContext().sessionid=getIntent().getIntExtra("sessionid", -1);
				changeToActivity(SNS.class);
			}
		});
        Cursor s=listdb.rawQuery("select * from sessions where _id="+getWCAppContext().sessionid, null);
        if (s.moveToFirst()){
        	UserInfoData userdata = MyHelper.get(this).getCurrUserInfoData(getWCAppContext().email);
        	if (s.getLong(1)!=userdata._id){
        		TextView yhCode=(TextView) client.findViewById(R.id.txtyhcode);
        		yhCode.setText("只有发起人才能看见优惠码");
        	}
        	s.close();
        }
        else{
    		TextView yhCode=(TextView) client.findViewById(R.id.txtyhcode);
    		yhCode.setText("只有订餐发起人才能看见优惠码");
        }

		Button btnsms=(Button)client.findViewById(R.id.btnsms);
		btnsms.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				UserInfoData myinfo = MyHelper.get(ShowSessionDetail.this).getCurrUserInfoData(getWCAppContext().email);
				Intent it = new Intent(Intent.ACTION_VIEW);    
				it.putExtra("sms_body", myinfo.username+"已使用 微餐 完成点餐，微餐可以协同点餐，还可享受额外折扣，简单实用，推荐你用一下，下载地址: http://m.weican.com/ 记得安装后加我。");    
				it.setType("vnd.android-dir/mms-sms");    
				startActivity(it);   
			}
		});
	}

	protected void refreshSessionDetail() {
		if (listdb!=null){
			Cursor c=listdb.rawQuery("select dishes._id,dishes.name,'' || count || ' * ' || dishes.price || '元' as count  from (select *,sum(total) as count from sessiondish where sessionid="
							+getIntent().getIntExtra("sessionid", -1)+" group by dishid) as ta,dishes where ta.dishid=dishes._id", null);
			startManagingCursor(c);
			ListAdapter listAdapter = new SessionSimpleCursorAdapter(this, R.layout.itemsessiondetail,
					c,
					new String[]{"name","count"},
					new int[]{R.id.txtname,R.id.txtprice});
			lstSessionDetail.setAdapter(listAdapter);
			Cursor t=listdb.rawQuery("select sum(count*price) as sum from (select  count,price from (select *,sum(total) as count from sessiondish where sessionid="
							+getIntent().getIntExtra("sessionid", -1)+" group by dishid) as ta,dishes where ta.dishid=dishes._id)", null);
			t.moveToFirst();
			txtTotal.setText("总价 "+t.getDouble(0)+" 元");
			t.close();
			lstSessionDetail.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					final long id=arg3;
					Cursor c=listdb.rawQuery("select * from dishes where _id="+id, null);
					c.moveToFirst();
					new AlertDialog.Builder(ShowSessionDetail.this).setTitle("加入收藏")
						.setMessage("您确定要把 "+c.getString(2)+" 加入到您的收藏吗？")
						.setPositiveButton("确定", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								UserInfoData userinfo = MyHelper.get(ShowSessionDetail.this).getCurrUserInfoData(getWCAppContext().email);
								Cursor c=listdb.rawQuery("select * from favorites where uid="+userinfo._id+" and dishid="+id, null);
								if (c.moveToFirst()){
									Toast.makeText(ShowSessionDetail.this, "已收藏", Toast.LENGTH_SHORT).show();
									c.close();
									return;
								}
								c.close();
								SQLiteDatabase db = MyHelper.get(ShowSessionDetail.this).getWritableDatabase();
								db.execSQL("insert into favorites (dishid,uid,timestamp) values ("+id+","+userinfo._id+","+new Date().getTime()+") "); 
								db.close();
								Toast.makeText(ShowSessionDetail.this, "操作成功", Toast.LENGTH_SHORT);
							}
						}).setNegativeButton("不用了", null).create().show();
					c.close();
				}
			});
		}
	}

	protected void onDestroy() {
        super.onDestroy();
        listdb.close(); //断开和数据库的连接，释放相关资源
    }

	@Override
	protected int getLayoutRes() {
		return R.layout.layoutsessiondetail;
	}

	/*
	@Override  
	public void onActivityResult(int reqCode, int resultCode, Intent data) {  
	    super.onActivityResult(reqCode, resultCode, data);  
	    if (resultCode == Activity.RESULT_OK) {  
	        Uri contactData = data.getData();  
	        Cursor c =  managedQuery(contactData, null, null, null, null);  
	        if (c.moveToFirst()) {  
	            c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 
	            String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
                final ArrayList<String>itemlist=new ArrayList<String>();
	            if (Integer.parseInt(c.getString(
	                    c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
	                 Cursor pCur = managedQuery(
	                 ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
	                 null, 
	                 ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
	                 new String[]{contactId}, null);
	                 while (pCur.moveToNext()) {
	                	 itemlist.add(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
	                 } 
	                 pCur.close();
	             }
                String[] items=new String[itemlist.size()];
                itemlist.toArray(items);
                if (items.length<=0){
                	Toast.makeText(this, "您选择的联系人似乎没有有效的联系号码！", Toast.LENGTH_LONG).show();
                	return;
                }
	            new AlertDialog.Builder(this).setIcon(R.drawable.icon).setTitle("请选择接收短信的号码")
	            	//.setMessage("您选择的联系人 "+name+" 还不是"+getString(R.string.app_name)+"用户，您要发送短信通知它吗？")
	            	//.setView(view)
	            	.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							SmsManager smsManager = SmsManager.getDefault();
			                PendingIntent sentIntent = PendingIntent.getBroadcast(ShowSessionDetail.this, 0, new Intent(), 0);
			                UserInfoData userinfo = MyHelper.get(ShowSessionDetail.this).getCurrUserInfoData(ShowSessionDetail.this.getWCAppContext().email);
			                String strContent="点餐完成，访问下面的网址获取详细信息";
			                String strNo=itemlist.get(selectNo);
			                if (strContent.length() > 70) {
			                    List<String> msgs = smsManager.divideMessage(strContent);
			                    for (String msg : msgs) {
			                        smsManager.sendTextMessage(strNo, null, msg, sentIntent, null);                        
			                    }
			                } else {
			                    smsManager.sendTextMessage(strNo, null, strContent, sentIntent, null);
			                }
			                Toast.makeText(ShowSessionDetail.this, "短信发送完成", Toast.LENGTH_LONG).show();
						}
					})
					.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int pos) {
							selectNo=pos;
						}
					  })
					.setNegativeButton("取消", null)
					.create().show();
	        }  
	    }  
	}*/
	
}
